﻿using PowerMonitor.BaseCtrl;
using PowerMonitor.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using PowerMonitor.Properties;

namespace PowerMonitor.History
{
    public partial class ReportView : Form
    {
       
        private List<BaseDevice> SelectedDevices = new List<BaseDevice>(); // 完整选择设备
        private List<DataItemTag> LooseSelItem = new List<DataItemTag>();        // 零散选择数据项
        private List<DataItemTag> SelectedItem = new List<DataItemTag>(); // 全部选择的数据项
        int LimitSeriesNum = 50; // 最多选择项数
        public enum eQueryType
        {
            day,
            month,
            year,
            custom
        }
        private eQueryType queryType = eQueryType.day;
        public ReportView()
        {
            InitializeComponent();
            
        }
        private void ReportView_Load(object sender, EventArgs e)
        {
            RefreshChlTree();
        }
        public void RefreshChlTree()
        {
            DevTreeview.Nodes.Clear(); // 清空所有
            int count = 0;
            foreach (var chl in AppMain.ChlList)
            {
                TriStateTreeNode chlNode = new TriStateTreeNode(chl.baseChlPara.ChannelName, 1, 0);

                chlNode.CheckboxVisible = true;
                chlNode.IsContainer = true;  // 添加此句才有三态 CheckBox
                chlNode.Tag = chl;
                DevTreeview.Nodes.Add(chlNode);
                //chlNode.Expand();
                for (int i = 0; i < chl.GetDevicesCnt(); i++)
                {
                    var dev = chl.GetDevByIndex(i);
                    TriStateTreeNode devNode = new TriStateTreeNode(dev.Name, 3, 2);
                    devNode.CheckboxVisible = true;
                    devNode.IsContainer = true;  // 添加此句才有三态 CheckBox
                    devNode.Tag = dev;
                    count = 0;
                    List<DevDataItem> itemlist = dev.GetDataList();
                    foreach (var item in itemlist)
                    {
                        if (cbbShowSaveSetted.Checked == true) // 只显示设置了保存的数据项
                        {
                            if (!item.IsSave)
                            {
                                continue;
                            }
                        }
                        if (ckbShowSumOnly.Checked)
                        {
                            if (!item.IsSummation)
                            {
                                continue;
                            }
                        }
                        count++;
                        TriStateTreeNode ItemNode = new TriStateTreeNode(item.Name, 3, 2);
                        ItemNode.CheckboxVisible = true;
                        DataItemTag itemTag = new DataItemTag((UInt32)chl.baseChlPara.ChannelId, (UInt32)dev.DeviceId, item);
                        ItemNode.Tag = itemTag;
                        devNode.Nodes.Add(ItemNode);
                    }
                    if (count > 0)
                    {
                        chlNode.Nodes.Add(devNode);
                    }
                }
                //chlNode.Expand();
            }
            if (DevTreeview.Nodes.Count > 0)
            {
                DevTreeview.Nodes[0].Expand();
                if (DevTreeview.Nodes[0].Nodes.Count > 0)
                {
                    DevTreeview.Nodes[0].Nodes[0].Expand();
                }
            }
        }
        /// <summary>
        /// 显示项处理（Checked==true时  只显示设置了存储属性的数据项）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbbShowSaveSetted_Click(object sender, EventArgs e)
        {
            RefreshChlTree();
        }
        /// <summary>
        /// 获取选中项
        /// </summary>
        /// <returns></returns>
        public bool GetSelectedItem()
        {
            SelectedDevices.Clear();
            LooseSelItem.Clear();
            SelectedItem.Clear();
            bool isMoreThanLimit = false;
            if (DevTreeview.Nodes.Count == 0)
            {
                return false;
            }
            try
            {
                foreach (TriStateTreeNode chlNode in DevTreeview.Nodes)
                {
                    foreach (TriStateTreeNode devNode in chlNode.Nodes)
                    {
                        if (devNode.CheckState != CheckState.Unchecked)
                        {
                            if (devNode.CheckState == CheckState.Checked)
                            {
                                SelectedDevices.Add((BaseDevice)devNode.Tag);
                                BaseDevice dev = SelectedDevices[SelectedDevices.Count - 1];
                                List<DevDataItem> itemlist = dev.GetDataList();
                                foreach (var item in itemlist)
                                {
                                    if (cbbShowSaveSetted.Checked == true) // 只显示设置了保存的数据项
                                    {
                                        if (!item.IsSave)
                                        {
                                            continue;
                                        }
                                    }
                                    if (ckbShowSumOnly.Checked)
                                    {
                                        if (!item.IsSummation)
                                        {
                                            continue;
                                        }
                                    }
                                    if (SelectedItem.Count >= LimitSeriesNum)
                                    {
                                        isMoreThanLimit = true;
                                        break;
                                    }
                                    SelectedItem.Add(new DataItemTag((UInt32)dev.ChannelId, (UInt32)dev.DeviceId, item));
                                }
                            }
                            else
                            {
                                foreach (TriStateTreeNode itemNode in devNode.Nodes)
                                {
                                    if (itemNode.Checked)
                                    {
                                        if (SelectedItem.Count >= LimitSeriesNum)
                                        {
                                            isMoreThanLimit = true;
                                            break;
                                        }
                                        LooseSelItem.Add((DataItemTag)itemNode.Tag);
                                        SelectedItem.Add((DataItemTag)itemNode.Tag);
                                    }
                                }
                            }
                        }

                    }
                }
                if (isMoreThanLimit)
                {
                    MessageBox.Show(string.Format(Resources.txtOnlyTopNIsValid, LimitSeriesNum), Properties.Resources.msgTitleTip);
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
            return true;
        }


        private void rbDay_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rb = sender as RadioButton;
            if (rb == null)
            {
                return;
            }
            dtpFrom.Value = DateTime.Now;
            dtpTo.Value = DateTime.Now;
            lbFrom.Visible = false;
            lbTo.Visible = false;
            dtpTo.Visible = false;
            string strTimeFormat = "yyyy-MM-dd HH:mm";
            switch (Int32.Parse(rb.Tag.ToString()))
            {
                case 0: // 日报
                    strTimeFormat = "yyyy-MM-dd";
                    dtpFrom.Width = 100;
                    dtpFrom.ShowUpDown = false;
                    queryType = eQueryType.day;
                    break;
                case 1: // 月报
                    strTimeFormat = "yyyy-MM";
                    dtpFrom.Width = 80;
                    dtpFrom.ShowUpDown = true;
                    queryType = eQueryType.month;
                    break;
                case 2: // 年报
                    strTimeFormat = "yyyy";
                    dtpFrom.Width = 60;
                    dtpFrom.ShowUpDown = true;
                    queryType = eQueryType.year;
                    break;
                case 3: // 自定义时间段
                    strTimeFormat = "yyyy-MM-dd HH:mm";
                    lbFrom.Visible = true;
                    dtpFrom.ShowUpDown = false;
                    dtpFrom.Value = dtpTo.Value.AddDays(-1);
                    lbTo.Visible = true;
                    dtpTo.Visible = true;
                    dtpFrom.Width = 136;
                    queryType = eQueryType.custom;
                    break;
                default:
                    strTimeFormat = "yyyy-MM-dd";
                    dtpFrom.ShowUpDown = false;
                    break;
            }
            dtpFrom.CustomFormat = strTimeFormat;
        }

        private int GetMonthMaxDay(int year, int month)
        {
            int maxday = 31;
            List<int> Max31 = new List<int> { 1, 3, 5, 7, 8, 10, 12 };
            List<int> Max30 = new List<int> { 4, 6, 9, 11 };
            if (month > 12 || month < 1)
            {
                return maxday;
            }
            if (Max31.Contains(month))
            {
                return maxday;
            }
            if (Max30.Contains(month))
            {
                return maxday - 1;
            }
            if (year % 4 == 0 || (year % 100 == 0 && year % 400 == 0))
            {
                return 29;
            }
            else
            {
                return 28;
            }
        }


        // 计算最大最小值  DataTable.Compute()
        private void FillDataToDataGrid(eQueryType querytype, Dictionary<UInt64, float> data, DataGridView dgv)
        {
            dgv.Rows.Clear();
            dgv.Columns.Clear();
            if (data.Count == 0 && querytype == eQueryType.custom)
            {
                return;
            }
            int i;
            dgv.SuspendLayout();
            UInt64 recordId = 0;
            int maxday = 30;
            BaseDevice dev = null;
            switch (querytype)
            {
                case eQueryType.day:
                    if (dgv.ColumnCount == 0)
                    {
                        dgv.Columns.Add(Resources.txtRecordHour, Resources.txtRecordHour);
                        dgv.Columns[0].Frozen = true;
                        dgv.Columns[0].DefaultCellStyle.BackColor = Color.SkyBlue;
                    }
                    dgv.Rows.Add(24);
                    for (i = 0; i < 24; i++)
                    {
                        dgv.Rows[i].Cells[0].Value = string.Format("{0:D2}:00", i);
                        dgv.Rows[i].Cells[0].Tag = (UInt64)(dtpFrom.Value.Day << 16) + (UInt64)(i << 8);
                    }
                    foreach (var item in SelectedItem)
                    {
                        dev = AppMain.ChlList[(int)item.ChannelId].GetDevByIndex((int)item.DeviceId);
                        if (dev != null)
                        {
                            dgv.Columns.Add(item.dataItem.Name, dev.Name + "\r\n" + item.dataItem.Name);
                        }
                        else
                        {
                            dgv.Columns.Add(item.dataItem.Name, item.dataItem.Name);
                        }
                        if (!item.dataItem.IsSummation) // 瞬时值
                        {
                            for (i = 0; i < 24; i++) // 每行
                            {
                                recordId = (UInt64)((UInt64)item.GlobalId << 32) + (UInt64)dgv.Rows[i].Cells[0].Tag;
                                if (data.ContainsKey(recordId))
                                {
                                    dgv.Rows[i].Cells[dgv.ColumnCount - 1].Value = data[recordId];
                                }
                                else
                                {
                                    dgv.Rows[i].Cells[dgv.ColumnCount - 1].Value = "-";
                                }
                            }
                        }
                        else // 累加值
                        {
                            UInt64 dRecordId;
                            for (i = 0; i < 24; i++) // 每行
                            {
                                if (i == 23)
                                {
                                    dRecordId = (UInt64)((UInt64)item.GlobalId << 32) + (UInt64)((dtpFrom.Value.Day + 1) << 16);
                                }
                                else
                                {
                                    dRecordId = (UInt64)((UInt64)item.GlobalId << 32) + (UInt64)(dtpFrom.Value.Day << 16) + (UInt64)((i + 1) << 8); ;
                                }
                                recordId = (UInt64)((UInt64)item.GlobalId << 32) + (UInt64)dgv.Rows[i].Cells[0].Tag;
                                if (data.ContainsKey(recordId) && data.ContainsKey(dRecordId))
                                {
                                    dgv.Rows[i].Cells[dgv.ColumnCount - 1].Value = data[dRecordId] - data[recordId];
                                }
                                else
                                {
                                    dgv.Rows[i].Cells[dgv.ColumnCount - 1].Value = "-";
                                }
                            }
                        }
                    }
                    break;
                case eQueryType.month:
                    if (dgv.ColumnCount == 0)
                    {
                        dgv.Columns.Add(Resources.txtRecordDay, Resources.txtRecordDay);
                        dgv.Columns[0].Frozen = true;
                        dgv.Columns[0].DefaultCellStyle.BackColor = Color.SkyBlue;
                    }
                    dgv.Rows.Add(31);
                    for (i = 0; i < 31; i++)
                    {
                        dgv.Rows[i].Cells[0].Value = string.Format("{0:D2}", i + 1);
                        dgv.Rows[i].Cells[0].Tag = (UInt64)((i + 1) << 16);
                    }
                    maxday = GetMonthMaxDay(dtpFrom.Value.Year, dtpFrom.Value.Month); // 最大天数
                    foreach (var item in SelectedItem)
                    {
                        dev = AppMain.ChlList[(int)item.ChannelId].GetDevByIndex((int)item.DeviceId);
                        if (dev != null)
                        {
                            dgv.Columns.Add(item.dataItem.Name, dev.Name + "\r\n" + item.dataItem.Name);
                        }
                        else
                        {
                            dgv.Columns.Add(item.dataItem.Name, item.dataItem.Name);
                        }
                        if (!item.dataItem.IsSummation) // 瞬时值
                        {
                            for (i = 0; i < 31; i++) // 每行
                            {
                                recordId = (UInt64)((UInt64)item.GlobalId << 32) + (UInt64)dgv.Rows[i].Cells[0].Tag;
                                if (data.ContainsKey(recordId))
                                {
                                    dgv.Rows[i].Cells[dgv.ColumnCount - 1].Value = data[recordId];
                                }
                                else
                                {
                                    dgv.Rows[i].Cells[dgv.ColumnCount - 1].Value = "-";
                                }
                            }
                        }
                        else // 累加值
                        {
                            UInt64 mRecordId = 0;
                            for (i = 0; i < 31; i++) // 每行
                            {
                                if (maxday == i + 1)
                                {
                                    recordId = (UInt64)((UInt64)item.GlobalId << 32) + (UInt64)((Int32)(maxday << 16));
                                    mRecordId = (UInt64)((UInt64)item.GlobalId << 32) + (UInt64)65536;
                                    if (QueryResultListTag.ContainsKey(mRecordId) && data.ContainsKey(recordId))
                                    {
                                        dgv.Rows[i].Cells[dgv.ColumnCount - 1].Value = QueryResultListTag[mRecordId] - data[recordId];
                                    }
                                    else
                                    {
                                        dgv.Rows[i].Cells[dgv.ColumnCount - 1].Value = "-";
                                    }
                                }
                                else if (maxday > i)
                                {
                                    recordId = (UInt64)((UInt64)item.GlobalId << 32) + (UInt64)((i + 1) << 16);
                                    mRecordId = (UInt64)((UInt64)item.GlobalId << 32) + (UInt64)((i + 2) << 16);
                                    if (data.ContainsKey(recordId) && data.ContainsKey(mRecordId))
                                    {
                                        dgv.Rows[i].Cells[dgv.ColumnCount - 1].Value = data[mRecordId] - data[recordId];

                                    }
                                    else
                                    {
                                        dgv.Rows[i].Cells[dgv.ColumnCount - 1].Value = "-";
                                    }
                                }
                                else
                                {
                                    dgv.Rows[i - 1].Cells[dgv.ColumnCount - 1].Value = "-";
                                }
                            }
                        }
                    }
                    break;
                case eQueryType.year:
                    if (dgv.ColumnCount == 0)
                    {
                        dgv.Columns.Add(Resources.txtRecordMonth, Resources.txtRecordMonth);
                        dgv.Columns[0].Frozen = true;
                        dgv.Columns[0].DefaultCellStyle.BackColor = Color.SkyBlue;
                    }
                    dgv.Rows.Add(12);
                    for (i = 0; i < 12; i++)
                    {
                        dgv.Rows[i].Cells[0].Value = string.Format("{0:D2}", i + 1);
                        dgv.Rows[i].Cells[0].Tag = (UInt64)(i + 1);
                    }

                    foreach (var item in SelectedItem)
                    {
                        dev = AppMain.ChlList[(int)item.ChannelId].GetDevByIndex((int)item.DeviceId);
                        if (dev != null)
                        {
                            dgv.Columns.Add(item.dataItem.Name, dev.Name + "\r\n" + item.dataItem.Name);
                        }
                        else
                        {
                            dgv.Columns.Add(item.dataItem.Name, item.dataItem.Name);
                        }
                        if (!item.dataItem.IsSummation) // 瞬时值
                        {
                            for (i = 0; i < 12; i++) // 每行
                            {
                                maxday = GetMonthMaxDay(dtpFrom.Value.Year, i + 1);
                                recordId = (UInt64)((UInt64)item.GlobalId << 32) + (UInt64)((i + 1) << 24) + (UInt64)((Int32)(maxday << 16) + (Int32)(23 << 8) + (60 - item.dataItem.SaveCycle));
                                if (data.ContainsKey(recordId))
                                {
                                    dgv.Rows[i].Cells[dgv.ColumnCount - 1].Value = data[recordId];
                                }
                                else
                                {
                                    dgv.Rows[i].Cells[dgv.ColumnCount - 1].Value = "-";
                                }
                            }
                        }
                        else
                        {
                            UInt64 yRecordId;
                            for (i = 0; i < 12; i++) // 每行
                            {
                                recordId = (UInt64)((UInt64)item.GlobalId << 32) + (UInt64)((i + 1) << 24) + (UInt64)65536;
                                yRecordId = (UInt64)((UInt64)item.GlobalId << 32) + (UInt64)((i + 1) << 24) + (UInt64)((Int32)(maxday << 16) + (Int32)(23 << 8) + (60 - item.dataItem.SaveCycle));
                                if (data.ContainsKey(recordId) && data.ContainsKey(yRecordId))
                                {
                                    dgv.Rows[i].Cells[dgv.ColumnCount - 1].Value = data[yRecordId] - data[recordId];
                                }
                                else
                                {
                                    dgv.Rows[i].Cells[dgv.ColumnCount - 1].Value = "-";
                                }
                            }
                        }
                        //dgv.Columns.Add(item.Name, item.Name);

                    }

                    break;
                case eQueryType.custom:
                    if (dgv.ColumnCount == 0)
                    {
                        dgv.Columns.Add(Resources.txtRecordTime, Resources.txtRecordTime);
                        dgv.Columns[0].Frozen = true;
                        dgv.Columns[0].DefaultCellStyle.BackColor = Color.SkyBlue;
                    }
                    List<UInt32> savetime = new List<UInt32>();
                    Int32 rowIndex = 0;
                    UInt32 tempValue = 0;
                    foreach (var item in data)
                    {
                        tempValue = (UInt32)item.Key;
                        if (!savetime.Contains(tempValue))
                        {
                            savetime.Add(tempValue);
                            dgv.Rows.Add();
                            dgv.Rows[rowIndex].Cells[0].Value = string.Format("{0:D2}-{1:D2} {2:D2}:{3:D2}", dtpFrom.Value.Month, tempValue >> 16, tempValue >> 8 & 0x00FF, tempValue & 0x00FF);
                            dgv.Rows[rowIndex].Cells[0].Tag = tempValue;
                            rowIndex++;
                        }
                    }
                    foreach (var item in SelectedItem)
                    {
                        dev = AppMain.ChlList[(int)item.ChannelId].GetDevByIndex((int)item.DeviceId);
                        if (dev != null)
                        {
                            dgv.Columns.Add(item.dataItem.Name, dev.Name + "\r\n" + item.dataItem.Name);
                        }
                        else
                        {
                            dgv.Columns.Add(item.dataItem.Name, item.dataItem.Name);
                        }

                        for (i = 0; i < dgv.RowCount; i++) // 每行
                        {
                            recordId = (UInt64)((UInt64)item.GlobalId << 32) + (UInt32)dgv.Rows[i].Cells[0].Tag;
                            if (data.ContainsKey(recordId))
                            {
                                dgv.Rows[i].Cells[dgv.ColumnCount - 1].Value = data[recordId];
                            }
                            else
                            {
                                dgv.Rows[i].Cells[dgv.ColumnCount - 1].Value = "-";
                            }
                        }
                    }
                    break;
                default:
                    break;
            }

            for (i = 0; i < dgv.ColumnCount; i++)
            {
                if (i == 0 && querytype == eQueryType.custom)
                {
                    dgv.Columns[0].SortMode = DataGridViewColumnSortMode.Automatic;
                }
                else
                {
                    dgv.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                }
            }
            dgv.ResumeLayout();
        }


        UInt32 dataidFrom = 0, dataidTo = 100;
        /// <summary>
        ///  保存查询结果（数据项标号，时标，数值；自定义查询时为时标，数据项标号，数值）
        /// </summary>
        Dictionary<UInt64, float> QueryResultList = new Dictionary<UInt64, float>();  // 某个数据项的不同时刻的值
        Dictionary<UInt64, float> QueryResultListTag = new Dictionary<UInt64, float>();  // 某个数据项的不同时刻的值(附加)
        private void btnQuery_Click(object sender, EventArgs e)
        {
            if (!GetSelectedItem())
            {
                MessageBox.Show(Resources.txtSelectErr, Properties.Resources.msgTitleTip, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (SelectedItem == null || SelectedItem.Count == 0)
            {
                //ControlExs.QQMessageBox.Show(null, Color.Green, "请选择需要查询的数据点!");
                MessageBox.Show(Resources.txtSelectNothing, Properties.Resources.msgTitleTip, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            string strTable0 = "", strTable1 = "";
            string strSQL = "", strSQLAll = "";

            strTable0 = Properties.Resources.HistoryTableName + dtpFrom.Value.ToString("yyyyMM");
            strTable1 = Properties.Resources.HistoryTableName + dtpTo.Value.ToString("yyyyMM");

            try
            {
                switch (queryType)
                {
                    case eQueryType.day:
                        strSQL = string.Format("savetime >= {0:D} and savetime <= {1:D} and (savetime mod 256=0) ", (Int32)(dtpFrom.Value.Day << 16), (Int32)((dtpFrom.Value.Day + 1) << 16));
                        break;
                    case eQueryType.month:
                        strSQL = "savetime % 65536=0";
                        break;
                    case eQueryType.year:
                        strSQL = string.Format("select name from MSysObjects where type=1 and flags=0 and name like '{0}%'", Properties.Resources.HistoryTableName + dtpFrom.Value.Year.ToString("D4"));
                        break;
                    case eQueryType.custom:
                        if (dtpTo.Value <= dtpFrom.Value || dtpTo.Value.Month != dtpFrom.Value.Month)
                        {
                            MessageBox.Show(Resources.txtSelectErrDate);
                            break;
                        }
                        strSQL = string.Format("savetime >= {0:D} and savetime <= {1:D}", (Int32)(dtpFrom.Value.Day << 16) + (Int32)(dtpFrom.Value.Hour << 8) + dtpFrom.Value.Minute,
                        (Int32)(dtpTo.Value.Day << 16) + (Int32)(dtpTo.Value.Hour << 8) + dtpTo.Value.Minute);
                        break;
                }
                if (strSQL == "")
                {
                    return;
                }
                QueryResultList.Clear();
                QueryResultListTag.Clear();

                UInt64 ItemId, TimeId;
                UInt64 RecordId;
                float fValue;
                DataTable dbTable = new DataTable();
                WaitingForm waiting = new WaitingForm((obj, arg) =>
                {
                        #region 自定义查询

                    if (queryType == eQueryType.custom) //  
                    {
                        if (SelectedDevices.Count > 0)
                        {
                            foreach (var dev in SelectedDevices)
                            {
                                if (dev.GetDataItemCnt() > 0)
                                {
                                    dataidFrom = (UInt32) (dev.ChannelId << 24) + (UInt32) (dev.DeviceId << 16) +
                                                 (UInt32) dev.GetDataItem(0).ItemId;
                                    dataidTo = (UInt32) (dev.ChannelId << 24) + (UInt32) (dev.DeviceId << 16) +
                                               (UInt32) dev.GetDataItem(dev.GetDataItemCnt() - 1).ItemId + 1;
                                }
                                else
                                {
                                    continue;
                                }
                                strSQLAll =
                                    string.Format(
                                        "select * from (select * from {0} where dataid >={1} and dataid < {2}) as OneDev  where {3}",
                                        strTable0, dataidFrom, dataidTo, strSQL);
                                dbTable = dbOper.GetDataTable(strSQLAll);
                                if (dbTable != null || dbTable.Rows.Count > 0)
                                {
                                    foreach (DataRow row in dbTable.Rows)
                                    {
                                        ItemId = Convert.ToUInt64(row.ItemArray[0]); // (UInt64)row.ItemArray[0] 会报错
                                        TimeId = Convert.ToUInt64(row.ItemArray[1]);
                                        RecordId = (UInt64) (ItemId << 32) + TimeId;
                                        fValue = Convert.ToSingle(row.ItemArray[2]);
                                        QueryResultList.Add(RecordId, fValue);
                                    }
                                }

                            }
                        }

                        if (LooseSelItem.Count > 0)
                        {
                            foreach (var item in LooseSelItem)
                            {
                                strSQLAll =
                                    string.Format(
                                        "select * from (select * from {0} where dataid={1} ) as OneDev  where {2}",
                                        strTable0, item.GlobalId, strSQL);
                                dbTable = dbOper.GetDataTable(strSQLAll);
                                if (dbTable == null || dbTable.Rows.Count == 0)
                                {
                                    continue;
                                }
                                foreach (DataRow row in dbTable.Rows)
                                {
                                    ItemId = Convert.ToUInt64(row.ItemArray[0]);
                                    TimeId = Convert.ToUInt64(row.ItemArray[1]);
                                    RecordId = (UInt64) (ItemId << 32) + TimeId;
                                    fValue = Convert.ToSingle(row.ItemArray[2]);
                                    QueryResultList.Add(RecordId, fValue);
                                }
                            }

                        }

                    }
                        #endregion
                        #region 年报查询

                    else if (queryType == eQueryType.year) // 年份查询
                    {
                        List<string> strtabName = new List<string>();
                        DataTable dtTableName = dbOper.GetDataTable(strSQLAll);
                        if (dtTableName == null)
                        {
                            MessageBox.Show(Resources.txtNothingSaved, Properties.Resources.msgTitleTip);
                            return;
                        }
                        foreach (DataRow row in dtTableName.Rows)
                        {
                            strtabName.Add((string) row.ItemArray[0]);
                        }

                        for (int i = 0; i < strtabName.Count; i++)
                        {
                            UInt64 month = UInt64.Parse(strtabName[i].Substring(strtabName[i].Length - 2, 2));
                            int maxday = GetMonthMaxDay(dtpFrom.Value.Year, (int) month);
                            if (SelectedItem.Count > 0)
                            {
                                foreach (var item in SelectedItem)
                                {
                                    strSQLAll =
                                        string.Format(
                                            "select * from (select * from {0} where dataid ={1}) as OneDev  where (savetime=65536 or savetime={2})",
                                            strtabName[i], item.GlobalId,
                                            (Int32) (maxday << 16) + (Int32) (23 << 8) +
                                            (Int32) (60 - item.dataItem.SaveCycle));
                                    dbTable = dbOper.GetDataTable(strSQLAll);
                                    if (dbTable == null || dbTable.Rows.Count == 0)
                                    {
                                        continue;
                                    }
                                    foreach (DataRow row in dbTable.Rows)
                                    {
                                        ItemId = Convert.ToUInt64(row.ItemArray[0]);
                                        TimeId = Convert.ToUInt64(row.ItemArray[1]);
                                        RecordId = (UInt64) (ItemId << 32) + TimeId + (UInt64) (month << 24);
                                        //RecordId = (UInt64)(ItemId << 32) + month;
                                        fValue = Convert.ToSingle(row.ItemArray[2]);
                                        QueryResultList.Add(RecordId, fValue);
                                    }
                                }
                            }
                        }

                    }
                        #endregion
                        #region 月报查询

                    else if (queryType == eQueryType.month) // 月份查询
                    {
                        strTable1 = Properties.Resources.HistoryTableName +
                                    dtpFrom.Value.AddMonths(1).ToString("yyyyMM");
                        if (SelectedDevices.Count > 0)
                        {
                            foreach (var dev in SelectedDevices)
                            {
                                if (dev.GetDataItemCnt() > 0)
                                {
                                    dataidFrom = (UInt32) (dev.ChannelId << 24) + (UInt32) (dev.DeviceId << 16) +
                                                 (UInt32) dev.GetDataItem(0).ItemId;
                                    dataidTo = (UInt32) (dev.ChannelId << 24) + (UInt32) (dev.DeviceId << 16) +
                                               (UInt32) dev.GetDataItem(dev.GetDataItemCnt() - 1).ItemId + 1;
                                }
                                else
                                {
                                    continue;
                                }
                                strSQLAll =
                                    string.Format(
                                        "select * from (select * from {0} where dataid >={1} and dataid < {2}) as OneDev  where {3}",
                                        strTable0, dataidFrom, dataidTo, strSQL);
                                dbTable = dbOper.GetDataTable(strSQLAll);
                                if (dbTable != null || dbTable.Rows.Count > 0)
                                {
                                    foreach (DataRow row in dbTable.Rows)
                                    {
                                        ItemId = Convert.ToUInt64(row.ItemArray[0]);
                                        TimeId = Convert.ToUInt64(row.ItemArray[1]);
                                        RecordId = (UInt64) (ItemId << 32) + TimeId;
                                        fValue = Convert.ToSingle(row.ItemArray[2]);
                                        QueryResultList.Add(RecordId, fValue);
                                    }
                                }
                                strSQLAll =
                                    string.Format(
                                        "select * from (select * from {0} where dataid >={1} and dataid < {2}) as OneDev  where savetime =65536",
                                        strTable1, dataidFrom, dataidTo);
                                dbTable = dbOper.GetDataTable(strSQLAll);
                                if (dbTable != null || dbTable.Rows.Count > 0)
                                {
                                    foreach (DataRow row in dbTable.Rows)
                                    {
                                        ItemId = Convert.ToUInt64(row.ItemArray[0]);
                                        TimeId = Convert.ToUInt64(row.ItemArray[1]);
                                        RecordId = (UInt64) (ItemId << 32) + TimeId;
                                        fValue = Convert.ToSingle(row.ItemArray[2]);
                                        QueryResultListTag.Add(RecordId, fValue);
                                    }
                                }
                            }
                        }
                        if (LooseSelItem.Count > 0)
                        {
                            foreach (var item in LooseSelItem)
                            {
                                strSQLAll =
                                    string.Format(
                                        "select * from (select * from {0} where dataid={1} ) as OneDev  where {2}",
                                        strTable0, item.GlobalId, strSQL);
                                dbTable = dbOper.GetDataTable(strSQLAll);
                                if (dbTable == null || dbTable.Rows.Count == 0)
                                {
                                    continue;
                                }
                                foreach (DataRow row in dbTable.Rows)
                                {
                                    ItemId = Convert.ToUInt64(row.ItemArray[0]);
                                    TimeId = Convert.ToUInt64(row.ItemArray[1]);
                                    RecordId = (UInt64) (ItemId << 32) + TimeId;
                                    fValue = Convert.ToSingle(row.ItemArray[2]);
                                    QueryResultList.Add(RecordId, fValue);
                                }
                                if (!item.dataItem.IsSummation)
                                {
                                    continue;
                                }
                                strSQLAll =
                                    string.Format(
                                        "select * from (select * from {0} where dataid={1} ) as OneDev  where savetime =65536",
                                        strTable1, item.GlobalId);
                                dbTable = dbOper.GetDataTable(strSQLAll);
                                if (dbTable == null || dbTable.Rows.Count == 0)
                                {
                                    continue;
                                }
                                foreach (DataRow row in dbTable.Rows)
                                {
                                    ItemId = Convert.ToUInt64(row.ItemArray[0]);
                                    TimeId = Convert.ToUInt64(row.ItemArray[1]);
                                    RecordId = (UInt64) (ItemId << 32) + TimeId;
                                    fValue = Convert.ToSingle(row.ItemArray[2]);
                                    QueryResultListTag.Add(RecordId, fValue);
                                }
                            }
                        }
                    }
                        #endregion
                        #region 日报查询

                    else // 日报查询
                    {
                        if (SelectedDevices.Count > 0)
                        {
                            foreach (var dev in SelectedDevices)
                            {
                                if (dev.GetDataItemCnt() > 0)
                                {
                                    dataidFrom = (UInt32) (dev.ChannelId << 24) + (UInt32) (dev.DeviceId << 16) +
                                                 (UInt32) dev.GetDataItem(0).ItemId;
                                    dataidTo = (UInt32) (dev.ChannelId << 24) + (UInt32) (dev.DeviceId << 16) +
                                               (UInt32) dev.GetDataItem(dev.GetDataItemCnt() - 1).ItemId + 1;
                                }
                                else
                                {
                                    continue;
                                }
                                strSQLAll =
                                    string.Format(
                                        "select * from (select * from {0} where dataid >={1} and dataid < {2}) as OneDev  where {3}",
                                        strTable0, dataidFrom, dataidTo, strSQL);
                                dbTable = dbOper.GetDataTable(strSQLAll);
                                if (dbTable != null || dbTable.Rows.Count > 0)
                                {
                                    foreach (DataRow row in dbTable.Rows)
                                    {
                                        ItemId = Convert.ToUInt64(row.ItemArray[0]);
                                        TimeId = Convert.ToUInt64(row.ItemArray[1]);
                                        RecordId = (UInt64) (ItemId << 32) + TimeId;
                                        fValue = Convert.ToSingle(row.ItemArray[2]);
                                        QueryResultList.Add(RecordId, fValue);
                                    }
                                }
                            }
                        }
                        if (LooseSelItem.Count > 0)
                        {
                            foreach (var item in LooseSelItem)
                            {
                                strSQLAll =
                                    string.Format(
                                        "select * from (select * from {0} where dataid={1} ) as OneDev  where {2}",
                                        strTable0, item.GlobalId, strSQL);
                                dbTable = dbOper.GetDataTable(strSQLAll);
                                if (dbTable == null || dbTable.Rows.Count == 0)
                                {
                                    continue;
                                }
                                foreach (DataRow row in dbTable.Rows)
                                {
                                    ItemId = Convert.ToUInt64(row.ItemArray[0]);
                                    TimeId = Convert.ToUInt64(row.ItemArray[1]);
                                    RecordId = (UInt64) (ItemId << 32) + TimeId;
                                    fValue = Convert.ToSingle(row.ItemArray[2]);
                                    QueryResultList.Add(RecordId, fValue);
                                }
                            }
                        }
                    }

                    #endregion
                }, false, false);
                waiting.ShowDialog();
                FillDataToDataGrid(queryType, QueryResultList, dgvQueryData); // 显示查询结果
                ckbStatistic_CheckedChanged(sender, e);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

        }

        /// <summary>
        /// 导出到Excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExport_Click(object sender, EventArgs e)
        {
            if (dgvQueryData.RowCount > 0 && dgvQueryData.ColumnCount > 1)
            {
                if (dgvQueryData.RowCount * dgvQueryData.ColumnCount > 50000)
                {
                    MessageBox.Show(Resources.txtExportTooMuch);
                    return;
                }
                string strName = "";
                switch (queryType)
                {
                    case eQueryType.day:
                        strName = string.Format(Resources.txtDayReport, dtpFrom.Value.ToString("yyyy-MM-dd"));
                        break;
                    case eQueryType.month:
                        strName = string.Format(Resources.txtMonthReport, dtpFrom.Value.ToString("yyyy-MM"));
                        break;
                    case eQueryType.year:
                        strName = string.Format(Resources.txtYearReport, dtpFrom.Value.ToString("yyyy"));
                        break;
                    case eQueryType.custom:
                        strName = string.Format(Resources.txtCustomReport, dtpFrom.Value.ToString("yyyy-MM-dd HH:mm"), dtpTo.Value.ToString("yyyy-MM-dd HH:mm"));
                        break;
                }
                AppMain.DataGridViewCopyToExcel(dgvQueryData, strName);

            }
            else
            {
                MessageBox.Show(Resources.txtNothingToExport);
            }
        }
        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (dgvQueryData.RowCount > 0 && dgvQueryData.ColumnCount > 1)
            {
                string strName = "";
                switch (queryType)
                {
                    case eQueryType.day:
                        strName = string.Format(Resources.txtDayReport, dtpFrom.Value.ToString("yyyy-MM-dd"));
                        break;
                    case eQueryType.month:
                        strName = string.Format(Resources.txtMonthReport, dtpFrom.Value.ToString("yyyy-MM"));
                        break;
                    case eQueryType.year:
                        strName = string.Format(Resources.txtYearReport, dtpFrom.Value.ToString("yyyy"));
                        break;
                    case eQueryType.custom:
                        strName = string.Format(Resources.txtCustomReport, dtpFrom.Value.ToString("yyyy-MM-dd HH:mm"), dtpTo.Value.ToString("yyyy-MM-dd HH:mm"));
                        break;
                }
                SystemCommon.DataGridViewPrinter.DataGridViewToPrint(dgvQueryData, strName);
            }
            else
            {
                MessageBox.Show(Resources.txtNothingToPrint, Properties.Resources.msgTitleTip, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        /// <summary>
        /// 显示统计
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ckbStatistic_CheckedChanged(object sender, EventArgs e)
        {
            if (ckbStatistic.Checked && dgvQueryData.RowCount > 0 && dgvQueryData.ColumnCount > 1)
            {
                dgvQueryData.Rows.Add(4);
                dgvQueryData.Rows[dgvQueryData.RowCount - 4].Cells[0].Value = Resources.txtMinValue;
                dgvQueryData.Rows[dgvQueryData.RowCount - 3].Cells[0].Value = Resources.txtMaxValue;
                dgvQueryData.Rows[dgvQueryData.RowCount - 2].Cells[0].Value = Resources.txtAverValue;
                dgvQueryData.Rows[dgvQueryData.RowCount - 1].Cells[0].Value = Resources.txtSumValue;
                float ftemp = 0, fmin = 0, fmax = 0, fsum = 0;
                int ValidRowsCnt = 0;

                List<Int32> maxList = new List<Int32>();
                List<Int32> minList = new List<Int32>();
                for (int i = 1; i < dgvQueryData.ColumnCount; i++)
                {
                    fsum = 0;
                    ValidRowsCnt = 0;
                    maxList.Clear();
                    minList.Clear();
                    for (int j = 0; j < dgvQueryData.RowCount - 4; j++)
                    {
                        if (dgvQueryData.Rows[j].Cells[i].Value.ToString() != "-")
                        {
                            ftemp = float.Parse(dgvQueryData.Rows[j].Cells[i].Value.ToString());
                            if (ValidRowsCnt == 0)
                            {
                                fmin = ftemp;
                                fmax = ftemp;
                            }
                            if (ftemp < fmin)
                            {
                                fmin = ftemp;
                                minList.Clear();
                                minList.Add(j);
                            }
                            else if (ftemp == fmin)
                            {
                                minList.Add(j);
                            }
                            if (ftemp > fmax)
                            {
                                fmax = ftemp;
                                maxList.Clear();
                                maxList.Add(j);
                            }
                            else if (ftemp == fmax)
                            {
                                maxList.Add(j);
                            }
                            fsum += ftemp;
                            ValidRowsCnt++;
                        }
                    }
                    if (maxList.Count > 0)
                    {
                        foreach (var index in maxList)
                        {
                            dgvQueryData.Rows[index].Cells[i].Style.ForeColor = System.Drawing.Color.OrangeRed;
                        }
                    }
                    if (minList.Count > 0)
                    {
                        foreach (var index in minList)
                        {
                            dgvQueryData.Rows[index].Cells[i].Style.ForeColor = System.Drawing.Color.LightGreen;
                        }
                    }
                    dgvQueryData.Rows[dgvQueryData.RowCount - 4].Cells[i].Value = fmin;
                    dgvQueryData.Rows[dgvQueryData.RowCount - 4].Cells[i].Style.ForeColor = System.Drawing.Color.LightGreen;
                    dgvQueryData.Rows[dgvQueryData.RowCount - 3].Cells[i].Value = fmax;
                    dgvQueryData.Rows[dgvQueryData.RowCount - 3].Cells[i].Style.ForeColor = System.Drawing.Color.OrangeRed;
                    if (ValidRowsCnt == 0)
                    {
                        dgvQueryData.Rows[dgvQueryData.RowCount - 2].Cells[i].Value = 0;
                    }
                    else
                    {
                        dgvQueryData.Rows[dgvQueryData.RowCount - 2].Cells[i].Value = Math.Round(fsum / ValidRowsCnt, 3);
                    }
                    dgvQueryData.Rows[dgvQueryData.RowCount - 2].Cells[i].Style.ForeColor = System.Drawing.Color.CadetBlue;
                    dgvQueryData.Rows[dgvQueryData.RowCount - 1].Cells[i].Value = fsum;
                    dgvQueryData.Rows[dgvQueryData.RowCount - 1].Cells[i].Style.ForeColor = System.Drawing.Color.Goldenrod;

                }
            }
            else if (!ckbStatistic.Checked && dgvQueryData.RowCount > 4 && dgvQueryData.Rows[dgvQueryData.RowCount - 1].Cells[0].Value.ToString() == Resources.txtSumValue)
            {
                for (int i = 0; i < 4; i++)
                {
                    dgvQueryData.Rows.RemoveAt(dgvQueryData.RowCount - 1);
                }
            }
        }

     
    }
    public class DoubleBufferListView : DataGridView
    {
        public DoubleBufferListView()
        {
            //下面语句为开启双缓冲
            SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
            UpdateStyles();
        }
    }
}
